'use client';

import { useEffect, useRef, useState } from 'react';
import './StyleSelector.scss';
import { MenuItem, Select } from '@mui/material';
import { useRouter } from 'next/navigation';

const StyleSelector = ({ skuInfo }: { skuInfo: Obj }) => {
  const [styleList, setStyleList] = useState<any[]>([]);
  const router = useRouter();

  const initStyles = () => {
    const styles = skuInfo.options?.map((field: any) => {
      return {
        name: field,
        value: skuInfo.spec.find((sp: any) => sp.name == field)?.value,
        options: Array.from(
          new Set(skuInfo.variants.map((v: any) => v[field]))
        ),
      };
    });
    styles && setStyleList(styles);
  };
  const initStylesRef = useRef(initStyles);
  initStylesRef.current = initStyles;

  useEffect(() => {
    skuInfo && initStylesRef.current();
  }, [skuInfo]);

  const handleChange = (e: any) => {
    const clicked = e?.target;
    if (clicked) {
      const param = [...styleList];
      const sel = param.find((sty: any) => sty.name == clicked.name);
      if (sel) {
        sel.value = clicked.value;
        const objVariant = skuInfo.variants.find((v: any) =>
          param.every((p: any) => v[p.name] == p.value)
        );
        console.log(param, objVariant);
        objVariant && router.push('/product/' + objVariant.sku);
      }
    }
  };

  return (
    <div className="product-style-list">
      {styleList?.map((sty: any, index: number) => (
        <label
          key={'sty_' + index + '_' + sty.name}
          className="product-style-section"
        >
          <span className="product-style-name">{sty.name}:</span>
          {/* <select className="product-style-select">
            {sty.options?.map((opt: any, idx: number) => (
              <option
                key={sty.name + '_' + idx + '_' + opt}
                selected={opt === sty.valie}
                value={opt}
              >
                <span>{opt}</span>
              </option>
            ))}
          </select> */}
          <Select
            className="product-style-select"
            value={sty.value}
            onChange={handleChange}
            displayEmpty
            inputProps={{ 'aria-label': 'Without label' }}
            sx={{
              width: '100%',
              p: 0,
              '& .MuiSelect-select': { p: '8px 10px' },
              '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                borderColor: '#3b1364',
                borderWidth: '1px',
              },
            }}
            name={sty.name}
          >
            {sty.options?.map((opt: any, idx: number) => (
              <MenuItem
                key={sty.name + '_' + idx + '_' + opt}
                value={opt}
                sx={{ fontSize: '14px' }}
              >
                {opt}
              </MenuItem>
            ))}
          </Select>
        </label>
      ))}
    </div>
  );
};

export default StyleSelector;
